#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include "navigator.h"
#include "navigator-bar.h"
#include "navigator-bar-element.h"

NavigatorBar::NavigatorBar(QWidget *parent)
    : QWidget(parent), m_navigator(new Navigator(this))
{
    connect (m_navigator, &Navigator::elementAdded, this, &NavigatorBar::addElement);
    connect (m_navigator, &Navigator::lastElementRemoved, this, &NavigatorBar::removeLastElement);

    m_horizontalLayout = new QHBoxLayout(this);
    m_horizontalLayout->setContentsMargins(0, 0, 0, 0);
    m_horizontalLayout->setSpacing(1);
    m_horizontalLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding));
}

NavigatorBar::~NavigatorBar()
{
    while (m_elements.size())
        removeLastElement();
}

Navigator* NavigatorBar::navigator()
{
    return m_navigator;
}

const Navigator* NavigatorBar::navigator() const
{
    return m_navigator;
}

void NavigatorBar::addElement (const QString& name)
{
    Q_ASSERT(m_navigator->currentPosition() == m_elements.size());

    if (m_elements.size())
        m_elements.at(m_navigator->currentPosition()-1)->setAsCurrent(false);
    NavigatorBarElement* element = new NavigatorBarElement(name, ">", m_elements.size(), this);
    element->setAsCurrent(true);
    connect (element, &NavigatorBarElement::activated, this, &NavigatorBar::elementActivated);
    m_elements.append(element);

    m_horizontalLayout->insertWidget(m_horizontalLayout->count()-1, element);
}

void NavigatorBar::elementActivated (const int orderNumber)
{
    m_elements.at(m_navigator->currentPosition())->setAsCurrent(false);
    m_navigator->setCurrentPosition(orderNumber);
    m_elements.at(orderNumber)->setAsCurrent(true);
    emit activated(m_navigator->currentElement());
}

void NavigatorBar::removeLastElement()
{
    NavigatorBarElement* lastElement = m_elements.takeLast();
    delete lastElement;
}
